package org.edu.modules.kaoqin.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Week;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.system.query.QueryGenerator;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.kaoqin.dto.VeHrPerformanceDTO;
import org.edu.modules.kaoqin.entity.VeHrPerformance;
import org.edu.modules.kaoqin.service.IVeHrPerformanceService;
import org.edu.modules.teacher.service.IBaseTeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "ve_hr_performance")
@RestController
@RequestMapping("/hr/kaoqin/veHrPerformance")
@Slf4j
public class VeHrPerformanceController extends BaseController<VeHrPerformance, IVeHrPerformanceService> {
    @Autowired
    private IVeHrPerformanceService veHrPerformanceService;
    @Autowired
    private IBaseTeacherService baseTeacherService;

    /**
     * 分页列表查询
     *
     * @param veHrPerformance
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ve_hr_performance-分页列表查询")
    @ApiOperation(value = "ve_hr_performance-分页列表查询", notes = "ve_hr_performance-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(VeHrPerformance veHrPerformance,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<VeHrPerformance> queryWrapper = QueryGenerator.initQueryWrapper(veHrPerformance, req.getParameterMap());

        Page<VeHrPerformance> page = new Page<VeHrPerformance>(pageNo, pageSize);
        IPage<VeHrPerformance> pageList = veHrPerformanceService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "我的绩效考勤分页列表查询")
    @ApiOperation(value = "我的绩效考勤分页列表查询", notes = "我的绩效考勤分页列表查询")
    @GetMapping(value = "/myList")
    public Result<IPage<VeHrPerformance>> queryMyPageList(VeHrPerformance veHrPerformance,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veHrPerformance.setUserid(sysUser.getId());
        // 周日期范围
        Date start = DateUtil.beginOfWeek(DateUtil.calendar()).getTime();
        Date end = DateUtil.endOfWeek(DateUtil.calendar()).getTime();


        QueryWrapper<VeHrPerformance> queryWrapper = QueryGenerator.initQueryWrapper(veHrPerformance, req.getParameterMap());
        queryWrapper.between("kqrq", start, end);
        Page<VeHrPerformance> page = new Page<VeHrPerformance>(pageNo, pageSize);
        IPage<VeHrPerformance> pageList = veHrPerformanceService.page(page, queryWrapper);
        Map<Date, VeHrPerformance> collect = pageList.getRecords().stream().collect(Collectors.toMap(VeHrPerformance::getKqrq, x -> x));


        ArrayList<VeHrPerformance> veHrPerformances = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            VeHrPerformance performance = new VeHrPerformance();
            performance.setUserid(sysUser.getId());
            DateTime dateTime = DateUtil.offsetDay(start, i);
            performance.setKqrq(dateTime);
            Week week = DateUtil.dayOfWeekEnum(dateTime);
            performance.setWeekName(week.toChinese("周"));

            VeHrPerformance orDefault = collect.getOrDefault(dateTime, new VeHrPerformance());
            performance.setId(orDefault.getId());
            performance.setSw(orDefault.getSw() == null ? 0 : orDefault.getSw());
            performance.setXw(orDefault.getXw() == null ? 0 : orDefault.getXw());
            performance.setWs(orDefault.getWs() == null ? 0 : orDefault.getWs());
            performance.setZb(orDefault.getZb() == null ? 0 : orDefault.getZb());
            veHrPerformances.add(performance);
        }
        pageList.setRecords(veHrPerformances);

        return Result.OK(pageList);
    }

    /**
     * 按天统计分页查询
     */
    @AutoLog(value = "按天统计分页查询")
    @ApiOperation(value = "按天统计分页查询", notes = "按天统计分页查询")
    @GetMapping(value = "/dayStatistic")
    public Result<?> dayStatistic(
            VeHrPerformanceDTO performanceDTO,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        Page<VeHrPerformanceDTO> page = new Page<VeHrPerformanceDTO>(pageNo, pageSize);

        return Result.OK(veHrPerformanceService.listByCondition(page, performanceDTO));
    }

    /**
     * 按天统计分页查询
     */
    @AutoLog(value = "按周统计分页查询")
    @ApiOperation(value = "按周统计分页查询", notes = "按周统计分页查询")
    @GetMapping(value = "/weekStatistic")
    public Result<?> weekStatistic(
            VeHrPerformanceDTO performanceDTO,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        Page<VeHrPerformanceDTO> page = new Page<VeHrPerformanceDTO>(pageNo, pageSize);

        return Result.OK(veHrPerformanceService.listByWeekStatistic(page, performanceDTO));
    }

    /**
     * 添加
     *
     * @param veHrPerformance
     * @return
     */
    @AutoLog(value = "ve_hr_performance-添加")
    @ApiOperation(value = "ve_hr_performance-添加", notes = "ve_hr_performance-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody VeHrPerformance veHrPerformance) {
        veHrPerformanceService.save(veHrPerformance);
        return Result.OK("添加成功！");
    }

    /**
     * 添加我的
     *
     * @param veHrPerformance
     * @return
     */
    @AutoLog(value = "添加我的绩效考核")
    @ApiOperation(value = "添加我的绩效考核", notes = "只能添加当天的")
    @PostMapping(value = "/addMy")
    public Result<?> addMy(@RequestBody VeHrPerformance veHrPerformance) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        veHrPerformance.setUserid(sysUser.getId());
//        veHrPerformance.setKqrq(DateUtil.date());
        veHrPerformanceService.saveOrUpdate(veHrPerformance, new LambdaQueryWrapper<VeHrPerformance>()
                .eq(VeHrPerformance::getKqrq, veHrPerformance.getKqrq())
                .eq(VeHrPerformance::getUserid, veHrPerformance.getUserid()));
        return Result.OK("添加成功！");
    }


    /**
     * 编辑
     *
     * @param veHrPerformance
     * @return
     */
    @AutoLog(value = "ve_hr_performance-编辑")
    @ApiOperation(value = "ve_hr_performance-编辑", notes = "ve_hr_performance-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody VeHrPerformance veHrPerformance) {
        veHrPerformanceService.updateById(veHrPerformance);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ve_hr_performance-通过id删除")
    @ApiOperation(value = "ve_hr_performance-通过id删除", notes = "ve_hr_performance-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        veHrPerformanceService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ve_hr_performance-批量删除")
    @ApiOperation(value = "ve_hr_performance-批量删除", notes = "ve_hr_performance-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.veHrPerformanceService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ve_hr_performance-通过id查询")
    @ApiOperation(value = "ve_hr_performance-通过id查询", notes = "ve_hr_performance-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        VeHrPerformance veHrPerformance = veHrPerformanceService.getById(id);
        if (veHrPerformance == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(veHrPerformance);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param veHrPerformance
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, VeHrPerformance veHrPerformance) {
        return super.exportXls(request, veHrPerformance, VeHrPerformance.class, "ve_hr_performance");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, VeHrPerformance.class);
    }

}
